package com.bbcare.treat.plat.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bbcare.comm.Constants;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.entity.PatientQueueScheme;
import com.bbcare.followup.plat.store.ibatis.IConfCacheDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientQueueSchemeDAO;
import com.bbcare.treat.plat.entity.PtTrQueue;
import com.bbcare.treat.plat.service.IPatientArchService;

import com.bbcare.treat.plat.store.ibatis.IPtArchiveDataDAO;
import com.bbcare.treat.plat.store.ibatis.IPtArchiveTaskDAO;
import com.bbcare.treat.plat.store.ibatis.IPtTrQueueDAO;

/**
 * @name: 患者门诊诊疗建档相关接口
 * @author:
 * @createTime: 2017.8.15
 * @description:
 * @modify:
 *
 */
@Service
public class PatientArchService implements IPatientArchService {
    private final Log logger = LogFactory.getLog(PatientArchService.class);

    @Autowired
    private IPatientQueueSchemeDAO patientQueueSchemeDao;

    @Autowired
    public IConfCacheDAO IConfCacheDAO;

    @Autowired
    private IPtArchiveTaskDAO ptArchiveTaskDao;

    @Autowired
    private IPtArchiveDataDAO ptArchiveDataDao;

    @Autowired
    private IPtTrQueueDAO ptTrQueueDao;

    /**
     * @name: 相同租户下不同队列建档信息修改接口
     * @author: DemonLee
     * @date: 2017.9.5
     * @description:同一租户下不同队列下修改建档基本信息， 导致用户基本信息pt_user_info一致（如姓名，手机号等），但建档信息pt_archivedata_info不一致
     * @modify: 后续用户按队列区分后，该接口要考虑废弃
     */
    @Override
    public Map<String, Object> dealOthQueuePtArchive(Map<String, Object> mapIn) throws Exception {
        Map<String, Object> mapOut = new HashMap<String, Object>();
        Map<String, Object> argMap = new HashMap<String, Object>(mapIn);

        Map<String, Object> taskInfo = ToolUtils.typeCast(argMap.get("taskInfo"));
        Map<String, Object> oprInfo = ToolUtils.typeCast(argMap.get("oprInfo"));
        String tenantId = (String) oprInfo.get("tenantId");
        String queueId = (String) oprInfo.get("followQueueId");
        String userId = (String) oprInfo.get("patientId");
        String ptSchemeId = (String) oprInfo.get("ptSchemeId");
        Map<String, Object> questions = ToolUtils.typeCast(argMap.get("questions"));

        // 问卷答案是否为空
        if (MapUtils.isEmpty(questions)) {
            return mapOut;
        }

        // 先查询该患者在同一租户非当前队列下是否加入过其他队列
        Map<String, Object> qryMapIn = new HashMap<String, Object>();
        qryMapIn.put("tenantId", tenantId);
        qryMapIn.put("revQueueId", queueId);
        qryMapIn.put("userId", userId);
        qryMapIn.put("revPtSchemeId", ptSchemeId);
        qryMapIn.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);
        List<PatientQueueScheme> pqsList = patientQueueSchemeDao.selectPatientByCondition(qryMapIn);
        if (CollectionUtils.isEmpty(pqsList)) {
            return mapOut;
        }

        // 逐个更新建档资料
        List<PtTrQueue> ptTrQueueList = null;
        PatientQueueScheme pqsVo = new PatientQueueScheme();
        int ip = 0;
        int ipsize = pqsList.size();
        for (ip = 0; ip < ipsize; ip++) {
            pqsVo = pqsList.get(ip);
            qryMapIn.clear();
            qryMapIn.put("ptSchemeId", pqsVo.getId());
            ptTrQueueList = ptTrQueueDao.getPtTrQueue(qryMapIn);
            if (CollectionUtils.isEmpty(ptTrQueueList)) {
                // 随访（后续再考虑）
                logger.warn("---该患者也加入了随访队列【" + pqsVo.getQueueId() + "】---");
            } else {
                // 诊疗
                oprInfo.put("followQueueId", pqsVo.getQueueId());
                oprInfo.put("ptSchemeId", pqsVo.getId());
                taskInfo.put("ptTaskId", pqsVo.getArchiveTaskId());
                this.saveOthQueuePtArchive(argMap);
            }
        }

        return mapOut;
    }

    /**
     * @name: 建档信息入表
     * @author: DemonLee
     * @date: 2017.9.5
     * @description:建档信息pt_archivedata_info入表
     * @modify:
     */
    public Map<String, Object> saveOthQueuePtArchive(Map<String, Object> mapIn) throws Exception {
        logger.info("in saveOthQueuePtArchive mapIn == " + mapIn.toString());
        Map<String, Object> mapOut = new HashMap<String, Object>();
        Map<String, Object> argMap = new HashMap<String, Object>(mapIn);

        Map<String, Object> oprInfo = ToolUtils.typeCast(argMap.get("oprInfo"));
        Map<String, Object> taskInfo = ToolUtils.typeCast(argMap.get("taskInfo"));
        Map<String, Object> questions = ToolUtils.typeCast(argMap.get("questions"));
        String updateAccept = (String) oprInfo.get("updateAccept");
        String updateTime = (String) oprInfo.get("updateTime");
        String authorId = (String) oprInfo.get("authorId");
        String sourceType = (String) oprInfo.get("sourceType");// 来源渠道
        String taskId = (String) taskInfo.get("ptTaskId");

        int iq = 0;
        int iqsize = Constants.QUESTION_ID_ARRAY_FOR_PT_USER_INFO.length;
        String queskey = "";
        String quesvalue = "";
        int pr = 0;
        Map<String, Object> ptUpMapIn = new HashMap<String, Object>();
        for (iq = 0; iq < iqsize; iq++) {
            queskey = Constants.QUESTION_ID_ARRAY_FOR_PT_USER_INFO[iq];
            quesvalue = (String) questions.get(queskey);
            if (null == quesvalue) {
                // 新修改的建档信息中无此题
                continue;
            }

            // 更新pt_archivedata_info
            ptUpMapIn.clear();
            ptUpMapIn.put("questionAnswer", quesvalue);
            ptUpMapIn.put("questionId", queskey);
            ptUpMapIn.put("ptTaskId", taskId);
            ptUpMapIn.put("updateAccept", updateAccept);
            ptUpMapIn.put("updateTime", updateTime);
            ptUpMapIn.put("sourceTypeUpdate", sourceType);
            pr = ptArchiveDataDao.modifyPtArchiveData(ptUpMapIn);
            if (0 == pr) {
                // 老的建档信息中无此题
                continue;
            }
        }

        // 更新pt_archivedata_info_his历史轨迹
        Map<String, Object> archMapIn = new HashMap<String, Object>();
        archMapIn.put("ptTaskId", taskId);
        archMapIn.put("updateAccept", updateAccept);
        archMapIn.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
        ptArchiveDataDao.savePtArchiveDataHis(archMapIn);

        // pt_archivetask_info更新及历史轨迹变化
        Map<String, Object> taskMap = new HashMap<String, Object>();
        taskMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
        taskMap.put("updateTime", updateTime);
        taskMap.put("updateAccept", updateAccept);
        taskMap.put("id", taskId);
        taskMap.put("updateAuthor", authorId);
        pr = ptArchiveTaskDao.updatePtArchiveTaskById(taskMap);

        taskMap.clear();
        taskMap.put("id", taskId);
        taskMap.put("updateType", Constants.UPDATE_TYPE_UPDATE_X);
        ptArchiveTaskDao.savePtArchiveTaskHis(taskMap);

        return mapOut;
    }

    // 队列建档任务不校验相关参数接口
    public boolean isVerifyArchiveParam(Map<String, Object> mapIn) throws Exception {
        String queueId = (String) mapIn.get("queueId");
        String quesId = (String) mapIn.get("quesId");
        if (StringUtils.isBlank(queueId) || StringUtils.isBlank(quesId)) {
            return true;
        }

        Map<String, Object> qryMapIn = new HashMap<String, Object>();
        qryMapIn.put("paramValue", quesId);
        qryMapIn.put("type", Constants.QUEUE_ARCHIVE_TASKCONT_NONVERIFY_TYPE);
        qryMapIn.put("paramCode", queueId);
        List<Map<String, Object>> retList = IConfCacheDAO.selectBsStaticParamByTenant(qryMapIn);
        if (CollectionUtils.isNotEmpty(retList)) {
            return false;
        }

        return true;
    }
}
